#include <stdbool.h>
#ifndef CONFIG_KERNEL_NONE
#include <aos/aos.h>
#include "k_api.h"
#include "platform.h"
#include "io_config.h"
#include "sleep.h"
#include "reg_syscfg.h"

bool mac_sleep();
void deep_sleep();
extern bool os_tick_updated;
void board_console_init();
void board_console_deinit();
static bool sleep_flag;

void tg7121b_sleep_enable(void)
{
    sleep_flag = true;
}

void tg7121b_sleep_disable(void)
{
    sleep_flag = false;
}

void tg7121b_standby_enable(void)
{
    struct deep_sleep_wakeup wakeup;

    memset(&wakeup, 0, sizeof(wakeup));
    wakeup.pb15 = 1;
    wakeup.pb15_rising_edge = 1;

    enter_deep_sleep_mode_lvl2_lvl3(&wakeup);
}

uint32_t tg7121b_get_bootup_reason(void)
{
    return SYSCFG->BKD[0];
}

int32_t tg7121b_set_bootup_reason(uint32_t reason)
{
    SYSCFG->BKD[0] = reason;

    return 0;
}

void krhino_idle_hook()
{
    if(sleep_flag == false)
    {
        return;
    }
    CPSR_ALLOC();
    RHINO_CRITICAL_ENTER();
    board_console_deinit();
    if(os_tick_updated && mac_sleep_check())
    {
        os_tick_updated = false;
        deep_sleep();
    }
    board_console_init();
    RHINO_CRITICAL_EXIT();
}

int32_t os_sleep_duration_get()
{
    int32_t suspend_tick = aos_kernel_suspend();
    return (uint32_t)OSTICK_HS_STEP_INC(CONFIG_SYSTICK_HZ,(uint32_t)suspend_tick);
}

#endif